import { useRef, useEffect, useState } from 'react'
import Copy from '$tp/copy'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $fn, $, $http, $config } = window
/* -------------------------------------------------------- Async Component -- */
import addConfig from './_config/add-field'
import modFieldName from './_config/mod-field-name'
import { modType } from './_config/mod-type'
import modNull from './_config/mod-null'
import modDefault from './_config/mod-default'
import modExtra from './_config/mod-extra'
import modComment from './_config/mod-comment'
import modSite from './_config/mod-site'
import modKey from './_config/mod-key'
import modAutoIncrement from './_config/mod-auto-increment'
import showTable from './_config/show-table'
import addKey from './_config/add-key'
import addForeignKey from './_config/add-foreign-key'
import showKey from './_config/show-key'
import showForeignKey from './_config/show-foreign-key'
// import showCreateTableSql from './_config/show-create-table-sql'
import CreateMigration from '../../_config/create-migration'

import CreateTempFile from '../../_config/create-temp-file'

import { getFrontData, getBackData } from '../../_utils/create-migration-tool'

import CopyFront from '../../_config/copy-front'
import CopyBack from '../../_config/copy-back'

const SearchTable = $lazy.hook(()=>import('#cpt/temp/SearchTable'))
const className = 'nosel cp abs_full fxm pl5'
const isNative = $config.isNative
/* -------------------------------------------------------- Page Component -- */
const Index = () => {
	const tableRef = useRef()
	const { t, d } = $fn.query()
	const table_name = t
	const [info, setInfo] = useState({ title:'', database: d })
	const [ schema, setSchema ] = useState({})
	const getSchemaTable = database => {
		$http.pull(null, 'mysql/show_information_schema_table', { param:{ table_name, database} }).then( d => setSchema(d[0]) )
	}
	useEffect(()=>{
		if(!d) {
			$http.pull(null, 'project/info', { loading:true }).then( d => {
				setInfo(d)
				getSchemaTable(d.database)
			})
		}else{
			getSchemaTable(d)
		}
	},[ d ]) // eslint-disable-line
	
	let temp = d || !isNative ? [] : [
		{ label:'生成模板', click: () => CreateTempFile({ is_structure:1, data:{ table_name, cols: $.ref(tableRef).tableRef().data() }, folder: info.folder, folder_front: info.folder_front })},
		{ label:'复制后端', ghost:1, click: () => CopyBack( getBackData( {  cols: $.ref(tableRef).tableRef().data() } ) ) },
		{ label:'复制前端', ghost:1, click: () => CopyFront( getFrontData({ cols: $.ref(tableRef).tableRef().data() }) ) },
		{ label:'生成 Migration', mode:'formModal', config:CreateMigration({ table_name, table_comment: schema?.table_comment, folder:info.folder, tableRef })},
	]
	
	const config = {
		page : {
			title: '表结构 - ' + info.database + ' - ' + table_name,
			minWidth:null,
			controls: {
				data: [
					...temp,
					!isNative ? null : { label:'设置自增起始点', mode:'formModal', ghost:1, config:modAutoIncrement({ table_name, database:info.database})},
					{ label:'查看表信息', mode:'tableModal', ghost:1, config:showTable({ table_name, database:info.database})},
					// { label:'查看 SQL', mode:'formModal', ghost:1, config:showCreateTableSql({ table_name, database:info.database})},
					{ label:'外键', mode:'dropdown', ghost:1, autoClose:1, data:[
						{ label:'添加外键', mode:'formModal', ghost:1, config:addForeignKey({ table_name, database:info.database, tableRef })},
						{ label:'查看表外键', mode:'tableModal', ghost:1, config:showForeignKey({ table_name, database:info.database, tableRef })},
						{ label:'查看所有表外键', mode:'tableModal', ghost:1, config:showForeignKey({ table_name, database:info.database, tableRef, all:1 })},
					]},
					{ label:'主键', mode:'dropdown', ghost:1, autoClose:1, data:[
						{ label:'添加主键', mode:'formModal', ghost:1, config:addKey({ table_name, database:info.database, tableRef })},
						{ label:'查看主键', mode:'tableModal', ghost:1, config:showKey({ table_name, database:info.database, tableRef })},
					]},
					{ mode:'add' },
					!isNative ? null : { mode:'del', abs:0, way:'put', param:{ database:info.database, table_name }, idStr:'Field' },
					{ mode:'back' }
				]
			}
		},
		search : {
			param: { database:info.database, table_name },
			data:[
				{ label:'字段名', 	name:'col_name' },
				{ label:'数据类型', 	name:'type' },
			]
		},
		// 表格配置
		table: {
			api:'mysql/structure',
			addApi: 'mysql/structure/save_field',
			modApi: 'mysql/structure/save_field',
			delApi: 'mysql/structure/del_field',
			param: { table_name, database:info.database },
			idStr: 'Field',
			paging:0,
			addConfig: addConfig({ database:info.database, table_name, tableRef }),
			row : {},
			cols:[
				{ title: '字段名', 			dataIndex: 'Field', 			width:120, render: (t,r) => {
					return (
						<div className={className} onClick={e=>e.stopPropagation()}>
							<div className='ex' onClick={ e => modFieldName({ e, data:r, table_name, database:info.database, tableRef })}><b className='ar f13'>{t}</b></div>
							<Copy t={t}/>
						</div>
					)
				} },
				{ title: '类型', 			dataIndex: 'Type', 				width:120, group:1, render: (t,r) => {
					return (
						<div className={className} onClick={e=>e.stopPropagation()}>
							<div className='ex' onClick={ e => modType({ e, data:r, table_name, database:info.database, tableRef })}><b className='c3 ar'>{t}</b></div>
							<Copy t={t}/>
						</div>
					)
				}},
				{ title: '是否空', 			dataIndex: 'Null', 				width:50, align:'center', render: (t,r) => {
					return (
						<div className={`${className} tc`} onClick={ e => modNull({ e, data:r, Null:t, table_name, database:info.database, tableRef })}>
							{t === 'NO' ? <b className='c1 ex'>{t}</b> : <b className='g9 ex'>{t}</b>}
						</div>
					)
				} },
				{ title: '主键类型', 		dataIndex: 'Key', 				width:50, align:'center', render: (t,r)=>{
					return (
						<div className={`${className} tc`} onClick={ e => modKey({ e, Field:r.Field, Type:r.Type, Key:t, table_name, database:info.database, tableRef })}>
							<b className='c4 ar ex'>{t}</b>
						</div>
					)
				}  },
				{ title: '默认值', 			dataIndex: 'Default', 			width:100, render: (t,r) => {
					return (
						<div className={className} onClick={e=>e.stopPropagation()}>
							<div className='ex h fxm' onClick={ e => modDefault({ e, data:r, Default:t, table_name, database:info.database, tableRef })}>
								{
									$fn.isString(t) ? <b className='g6 ar'>{t ? t.toLowerCase() : t}</b> : <b>{t}</b>
								}
							</div>
							{
								t ? <Copy t={$fn.isString(t) ? t.toLowerCase() : t}/> : null
							}
						</div>
					)
				} },
				{ title: '额外参数', 		dataIndex: 'Extra', 			width:100, render: (t,r) => {
					let is_def = t?.includes('DEFAULT_GENERATED')
					t = is_def ? t.replace('DEFAULT_GENERATED', '') : t
					return (
						<div className={className} onClick={e=>e.stopPropagation()}>
							<div className='ex h fxm omit' onClick={ e => modExtra({ e, data:r, Extra:t, table_name, database:info.database, tableRef })}>
								{
									<b className='ar c0'>{ t ? t.toLowerCase() : t }</b>
								}
							</div>
							{
								t ? <Copy t={t.toLowerCase()}/> : null
							}
						</div>
					)
				} },
				{ title: '注释', 			dataIndex: 'Comment', 			width:150, render: (t,r) => {
					return (
						<div className={className} onClick={e=>e.stopPropagation()}>
							<div className='ex h fxm omit' onClick={ e => modComment({ e, data:r, Comment:t, table_name, database:info.database, tableRef })}>
								<div className='ex omit'>{ t }</div>
							</div>
							{
								t ? <Copy t={t}/> : null
							}
						</div>
					)
				} },
				// { title: '编码', 			dataIndex: 'Collation', 		width:100 },
			],
			controls 	: {
				width: 150,
				data:  data => {
					const { Field, Type, Null, Key, Default, Extra, Comment } = data
					return [
						{ mode:'mod', infoApi: false, backData:{ Field, Type , Null: Null !== 'NO', Key, Default, Extra, Comment, id:1  }, config:addConfig({ database:info.database, table_name, tableRef }) },
						!isNative ? null : { mode:'delPop', abs:0, way:'put', param:{ database:info.database, table_name, Field },
							msg:<span>是否删除【<b className='ar c3'>{Field}</b>】字段?</span>
						},
						{ label:'位置', mode:'formModal', abs:0, way:'put', r:1, config: modSite({ database:info.database, table_name, data }) },
					]
				}
			}
		}
	}
	return info.database && <SearchTable {...config} ref={tableRef}/>
}
export default Index